import GpEffMaker from "./GpEffMaker";
import { Comp } from "../../m/CompDef";

import { _decorator, Component, Node, sp, Animation ,Tween} from 'cc';
import { BaseComponent } from "../../../../../extensions/cocos-scaffold-3x/assets/ui/base/BaseComponent";
import { EcsEntity } from "ecs-ts";
const { ccclass, property } = _decorator;


export class GpEffProp {
    constructor(
        public maker: GpEffMaker,
        public path: string,
        public followEntity: EcsEntity = null,
        public duration: number = 0,
    ) { }
}

@ccclass
export default class GpEff extends BaseComponent<GpEffProp> {

    onInit(): void {

        // console.log("SkEff onInit");
        const ske = this.node.getComponent(sp.Skeleton)
        const animation = this.node.getComponent(Animation)
        const duration = this.prop?.duration
        if (duration) {
            this.scheduleOnce(() => {
                this.prop.maker.removeEff(this)
            }, this.prop.duration)
        }
        if (ske) {
            // ske.animation = 'animation'

            if (!duration) {
                ske.setCompleteListener(() => {
                    this.prop.maker.removeEff(this)
                })
            }

        } else if (animation) {
            console.log("GpEff onInit animation");
            animation.play(animation.defaultClip.name)
            if (!duration) {
                animation.on(Animation.EventType.FINISHED, () => {
                    this.prop.maker.removeEff(this)
                })
            }
        }


    }


    protected onDisable(): void {
        Tween.stopAllByTarget(this.node)
        this.unscheduleAllCallbacks()
    }

    update(dt) {
        if (this.prop?.followEntity) {
            const pos = this.prop.followEntity.component(Comp.Transform).pos
            this.node.setPosition(pos.x, pos.y)
        }
    }
}
